<template>
  <div class="posts-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-button link @click="$router.push('/')" style="margin-right: 10px;">
            返回
          </el-button>
          <h2>动态广场</h2>
          <el-button type="primary" @click="showPostDialog = true">
            <el-icon><Edit /></el-icon>
            发布动态
          </el-button>
        </div>
      </template>
      
      <div class="posts-container">
        <div v-if="posts.length === 0" class="empty-state">
          <el-empty description="暂无动态，快来发布第一条吧！" />
        </div>
        <div v-else>
          <div v-for="post in posts" :key="post.id" class="post-item">
            <div class="post-header">
              <el-avatar :size="40" :src="post.avatar || ''" @click="showUserProfile(post.username)" style="cursor:pointer;">
                {{ post.username?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <div class="post-info">
                <h4 @click="goUserProfile(post.username)" style="cursor:pointer; color: #409EFF; text-decoration: underline;">{{ post.username }}</h4>
                <span class="post-time">{{ formatTime(post.targetDate) }}</span>
              </div>
            </div>
            <div class="post-content">
              <p>{{ post.description }}</p>
              <div v-if="post.imageUrls && post.imageUrls.length > 0" class="post-images">
                <el-image
                  v-for="(imageUrl, index) in post.imageUrls"
                  :key="index"
                  :src="imageUrl"
                  :preview-src-list="post.imageUrls"
                  fit="cover"
                  class="post-image"
                  :error="() => '加载失败'"
                />
              </div>
              <div v-if="post.videoUrls && post.videoUrls.length > 0" class="post-videos">
                <video v-for="(videoUrl, idx) in post.videoUrls" :key="idx" :src="videoUrl" controls style="width: 240px; border-radius: 8px; margin-top: 10px;" />
              </div>
            </div>
            <div class="post-actions">
              <el-button link v-if="!isLiked(post)" @click="likePost(post.id)">
                <el-icon><Star /></el-icon>
                {{ post.likes !== undefined ? post.likes : (post.likedUsers ? post.likedUsers.length : 0) }} 点赞
              </el-button>
              <el-button link v-else @click="unlikePost(post.id)">
                <el-icon><Star /></el-icon>
                已点赞
              </el-button>
              <el-button link @click="toggleComments(post.id)">
                <el-icon><ChatDotRound /></el-icon>
                {{ post.comments !== undefined ? post.comments : (post.commentCount !== undefined ? post.commentCount : (comments[post.id]?.length || 0)) }} 评论
              </el-button>
            </div>
            <div v-if="showingComments[post.id]" class="comments-section">
              <div class="comment-list">
                <div v-for="comment in comments[post.id] || []" :key="comment.id" class="comment-item">
                  <b>{{ comment.username }}</b>：{{ comment.content || comment.description }}
                </div>
              </div>
              <div style="margin-top: 18px;"></div>
              <el-input v-model="newComment[post.id]" placeholder="写评论..." @keyup.enter="submitComment(post.id)" />
              <el-button size="small" @click="submitComment(post.id)">评论</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发布动态对话框 -->
    <el-dialog
      v-model="showPostDialog"
      title="发布动态"
      width="500px"
    >
      <el-form :model="postForm" label-width="80px">
        <el-form-item label="内容">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="4"
            placeholder="分享你的想法..."
          />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload :auto-upload="false" :on-change="handleImageChange" :file-list="fileList" list-type="picture-card" :limit="5" accept="image/*">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频">
          <el-upload :auto-upload="false" :on-change="handleVideoChange" :file-list="videoFileList" list-type="text" :limit="1" accept="video/*">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPostDialog = false">取消</el-button>
          <el-button type="primary" @click="createPost" :loading="posting">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户资料浮窗 -->
    <el-dialog v-model="userProfileDialogVisible" :show-close="true" width="400px" :modal-append-to-body="false" :modal="true" :close-on-click-modal="true" class="user-profile-dialog">
      <user-profile-popup :username="selectedUsername" @close="userProfileDialogVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { postApi, fileApi } from '@/utils/api'
import { ElMessage } from 'element-plus'
import { Plus, Star, ChatDotRound } from '@element-plus/icons-vue'
import UserProfilePopup from '@/components/UserProfilePopup.vue'
import { useRouter } from 'vue-router'

export default {
  name: 'Posts',
  components: {
    Plus,
    Star,
    ChatDotRound,
    UserProfilePopup
  },
  setup() {
    const showPostDialog = ref(false)
    const posting = ref(false)
    const posts = ref([])
    const fileList = ref([])
    const videoFileList = ref([])
    const postForm = reactive({
      content: ''
    })
    const showingComments = reactive({})
    const comments = reactive({})
    const newComment = reactive({})
    const likedPosts = ref([])
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const userProfileDialogVisible = ref(false)
    const selectedUsername = ref('')
    const router = useRouter()

    const loadPosts = async () => {
      try {
        const response = await postApi.getAll()
        posts.value = response.data || []
        // 假设后端返回点赞用户列表 likedUsers
        likedPosts.value = posts.value.filter(p => (p.likedUsers || []).includes(user.username)).map(p => p.id)
      } catch (error) {
        ElMessage.error('加载动态失败: ' + (error.response?.data || error.message))
      }
    }

    const isLiked = (post) => likedPosts.value.includes(post.id)

    const likePost = async (postId) => {
      try {
        await postApi.like(postId)
        await loadPosts()
        ElMessage.success('点赞成功')
      } catch (error) {
        ElMessage.error('点赞失败: ' + (error.response?.data || error.message))
      }
    }

    const unlikePost = async (postId) => {
      try {
        await postApi.unlike(postId)
        await loadPosts()
        ElMessage.success('取消点赞成功')
      } catch (error) {
        ElMessage.error('取消点赞失败: ' + (error.response?.data || error.message))
      }
    }

    const toggleComments = async (postId) => {
      showingComments[postId] = !showingComments[postId]
      if (showingComments[postId]) {
        try {
          const res = await postApi.getComments(postId)
          comments[postId] = res.data
        } catch (e) {
          comments[postId] = []
        }
      }
    }

    const submitComment = async (postId) => {
      if (!newComment[postId]) return
      try {
        await postApi.comment({ postId, content: newComment[postId] })
        ElMessage.success('评论成功')
        newComment[postId] = ''
        await toggleComments(postId)
      } catch (error) {
        ElMessage.error('评论失败: ' + (error.response?.data || error.message))
      }
    }

    const handleImageChange = (file, fileListArr) => {
      fileList.value = fileListArr
    }

    const handleVideoChange = (file, fileListArr) => {
      videoFileList.value = fileListArr
    }

    const createPost = async () => {
      if (!postForm.content.trim()) {
        ElMessage.warning('请输入动态内容')
        return
      }
      try {
        posting.value = true
        let imageUrls = []
        for (const file of fileList.value) {
          if (file.raw) {
            const res = await fileApi.upload(file.raw)
            imageUrls.push(res.data.fileDownloadUri)
          }
        }
        let videoUrls = []
        for (const file of videoFileList.value) {
          if (file.raw) {
            const res = await fileApi.upload(file.raw)
            videoUrls.push(res.data.fileDownloadUri)
          }
        }
        await postApi.create({ description: postForm.content, imageUrls, videoUrls })
        ElMessage.success('发布成功')
        showPostDialog.value = false
        postForm.content = ''
        fileList.value = []
        videoFileList.value = []
        await loadPosts()
      } catch (error) {
        ElMessage.error('发布失败: ' + (error.response?.data || error.message))
      } finally {
        posting.value = false
      }
    }

    const formatTime = (time) => {
      if (!time) return ''
      try {
        return new Date(time).toLocaleString()
      } catch {
        return ''
      }
    }

    const showUserProfile = (username) => {
      selectedUsername.value = username
      userProfileDialogVisible.value = true
    }

    const goUserProfile = (username) => {
      if (!username) return;
      router.push({ name: 'UserProfile', params: { username } });
    }

    onMounted(() => {
      loadPosts()
    })

    return {
      showPostDialog,
      posting,
      posts,
      postForm,
      fileList,
      videoFileList,
      likePost,
      unlikePost,
      isLiked,
      showingComments,
      comments,
      newComment,
      toggleComments,
      submitComment,
      handleImageChange,
      handleVideoChange,
      createPost,
      formatTime,
      userProfileDialogVisible,
      selectedUsername,
      showUserProfile,
      goUserProfile
    }
  }
}
</script>

<style scoped>
.posts-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.posts-container {
  min-height: 400px;
}

.post-item {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.post-item:last-child {
  border-bottom: none;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.post-info {
  margin-left: 10px;
}

.post-info h4 {
  margin: 0 0 5px 0;
}

.post-time {
  color: #999;
  font-size: 12px;
}

.post-content {
  margin: 15px 0;
}

.post-content p {
  margin: 0 0 10px 0;
  line-height: 1.6;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.post-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

.post-videos {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.post-actions {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.comments-section {
  margin-top: 10px;
  background: #f7f7f7;
  border-radius: 6px;
  padding: 10px;
}

.comment-item {
  margin-bottom: 8px;
  padding: 4px 0;
  border-bottom: 1px solid #eee;
  font-size: 15px;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-list {
  margin-bottom: 18px;
}

.user-profile-dialog >>> .el-dialog__wrapper {
  background: rgba(0,0,0,0.4) !important;
}
</style> 